package top.anka1.fxgui;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;

import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import top.anka1.ims.*;
import top.anka1.ims.RestaurantManagementSystem.Meal;
import top.anka1.ims.RestaurantManagementSystem.RestaurantBilling;

import java.util.ArrayList;
/**
 * AddMealToOrderController is a controller class for adding meals to an order in a restaurant management system.
 * It handles the interaction between the GUI and the underlying data model.
 * @author Anka
 */
public class AddMealToOrderController {
    private RestaurantGUI restaurantGUI;
    private Stage stage;
    private ArrayList<RestaurantBilling> ordersList;
    private ArrayList<Meal> menuList;
    private ArrayList<Meal> orderList = new ArrayList<>();
    @FXML
    private TableView<Meal> menuTable;
    @FXML
    private TableColumn<Meal, String> menuNameColumn;
    @FXML
    private TableColumn<Meal, Double> menuPriceColumn;
    @FXML
    private TableView<Meal> orderTable;
    @FXML
    private TableColumn<Meal, String> orderNameColumn;
    @FXML
    private TableColumn<Meal, Double> orderPriceColumn;

    public void showError(Stage stage, String title, String HeaderText, String contentText) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.initOwner(stage);
        alert.setTitle(title);
        alert.setHeaderText(HeaderText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }
    public void showInformation(Stage stage, String title, String HeaderText, String contentText) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.initOwner(stage);
        alert.setTitle(title);
        alert.setHeaderText(HeaderText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }
    public void setData(RestaurantGUI restaurantGUI, Stage stage) {
        this.restaurantGUI = restaurantGUI;
        this.stage = stage;
        ordersList = restaurantGUI.getRestaurantService().getOrders();
        menuNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        menuNameColumn.setStyle("-fx-alignment: CENTER;");
        menuPriceColumn.setCellValueFactory(new PropertyValueFactory<>("totalPrice"));
        menuPriceColumn.setStyle("-fx-alignment: CENTER;");
        menuPriceColumn.setCellFactory(column -> new javafx.scene.control.cell.TextFieldTableCell<>(
                new javafx.util.converter.DoubleStringConverter() {
                    @Override
                    public String toString(Double value) {
                        if (value == null) return "";
                        return String.format("¥%.2f", value);
                    }
                }
        ));

        orderNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        orderNameColumn.setStyle("-fx-alignment: CENTER;");
        orderPriceColumn.setCellValueFactory(new PropertyValueFactory<>("totalPrice"));
        orderPriceColumn.setStyle("-fx-alignment: CENTER;");
        orderPriceColumn.setCellFactory(column -> new javafx.scene.control.cell.TextFieldTableCell<>(
                new javafx.util.converter.DoubleStringConverter() {
                    @Override
                    public String toString(Double value) {
                        if (value == null) return "";
                        return String.format("¥%.2f", value);
                    }
                }
        ));

        menuList = restaurantGUI.getRestaurantService().getMenu();
        ObservableList<Meal> meals = FXCollections.observableArrayList(menuList);
        menuTable.setItems(meals);
    }

    @FXML
    public void addToOrder() {
        Meal selectedMeal = menuTable.getSelectionModel().getSelectedItem();
        try {
            if (selectedMeal != null) {
                orderList.add(selectedMeal);
                ObservableList<Meal> orderMeals = FXCollections.observableArrayList(orderList);
                orderTable.setItems(orderMeals);
            } else {
                showError(stage, "Error", "No Meal Selected", "Please select a meal to add to the order.");
            }
        }catch (Exception e) {
            showError(stage, "Error", "Failed to add meal to order", "Error: " + e.getMessage());
        }
    }
    @FXML
    public void removeFromOrder() {
        Meal selectedMeal = orderTable.getSelectionModel().getSelectedItem();
        try {
            if (selectedMeal != null) {
                orderList.remove(selectedMeal);
                ObservableList<Meal> orderMeals = FXCollections.observableArrayList(orderList);
                orderTable.setItems(orderMeals);
            } else {
                showError(stage, "Error", "No Meal Selected", "Please select a meal to remove from the order.");
            }
        }catch (Exception e) {
            showError(stage, "Error", "Failed to remove meal from order", "Error: " + e.getMessage());
        }
    }
    @FXML
    public void confirmOrder() {
        try {
            if (orderList != null && !orderList.isEmpty()) {
                RestaurantBilling restaurantBilling = new RestaurantBilling();
                for (Meal meal : orderList) {
                    restaurantBilling.addMealToOrder(meal);
                }
                ordersList.add(restaurantBilling);
                showInformation(stage, "Success", "Order has been confirmed successfully.", "Your order ID is: " + ordersList.indexOf(restaurantBilling));
            } else {
                showError(stage, "Error", "No Meals in Order", "Please add meals to the order before confirming.");
                return;
            }
        } catch (Exception e) {
            showError(stage, "Error", "Failed to confirm order", "Error: " + e.getMessage());
            return;
        }
        stage.close();
    }
}
